﻿using Devonline.Core;
using Devonline.Database.NoSQL;
using Devonline.Entity;
using Microsoft.Extensions.Logging;
using MongoDB.Driver;

namespace Devonline.Database.MongoDB;

/// <summary>
/// MongoDB 数据服务得默认实现
/// </summary>
public class MongoDataService : NoSQLDataService, IMongoDataService
{
    private readonly IMongoDatabase _database;
    public MongoDataService(ILogger<NoSQLDataService> logger, IDatabaseEndpoint endpoint) : base(logger, endpoint)
    {
        _database = new MongoClient(endpoint.ConnectionString).GetDatabase(endpoint.Database);
    }

    /// <summary>
    /// 写入一行数据到数据库
    /// </summary>
    /// <typeparam name="TModel">数据对象模型的类型</typeparam>
    /// <param name="model">待写入的数据</param>
    /// <returns></returns>
    public override async Task WriteAsync<TModel>(TModel model) => await ExecuteWriteAsync(async () =>
    {
        var collection = await GetOrCreateCollectionAsync<TModel>();
        await collection.InsertOneAsync(model);
    });
    /// <summary>
    /// 写入多行数据到数据库
    /// </summary>
    /// <typeparam name="TModel">数据对象模型的类型</typeparam>
    /// <param name="data">待写入的数据</param>
    /// <returns></returns>
    public override async Task WritesAsync<TModel>(IEnumerable<TModel> data) => await ExecuteWriteAsync(async () =>
    {
        var collection = await GetOrCreateCollectionAsync<TModel>();
        await collection.InsertManyAsync(data);
    });

    /// <summary>
    /// 从数据库查询多行数据
    /// </summary>
    /// <typeparam name="TModel">数据对象模型的类型</typeparam>
    /// <typeparam name="TQueryRequest">查询请求表达式类型</typeparam>
    /// <param name="request">查询请求</param>
    /// <returns></returns>
    public override async Task<IEnumerable<TModel>> QueryAsync<TModel, TQueryRequest>(TQueryRequest request)
    {
        var collection = await GetOrCreateCollectionAsync<TModel>();
        //collection.FindAsync()
        return default;
    }

    /// <summary>
    /// 获取或创建 MongoDB 的数据集合
    /// </summary>
    /// <typeparam name="TModel">数据对象模型的类型</typeparam>
    /// <returns></returns>
    private async Task<IMongoCollection<TModel>> GetOrCreateCollectionAsync<TModel>()
    {
        var tableName = typeof(TModel).GetTableName() ?? _endpoint.DataTable;
        var collection = _database.GetCollection<TModel>(tableName);
        if (collection == null)
        {
            await _database.CreateCollectionAsync(tableName);
            collection = _database.GetCollection<TModel>(tableName);
        }

        return collection;
    }

    private void GetQueryRequest<TModel, TQueryRequest>(TQueryRequest request)
    {
        if (request is MongoQueryRequest queryRequest)
        {

        }
    }
}